package com.wf.course.web.Interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.ListUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.wf.course.web.Constants;

import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;

/**
 * 简单的权限拦截器
 * @author lyinlong
 *
 */
public class AccessInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		ResourceBundle resource = ResourceBundle.getBundle("global");
		String IGNORE_PATH = resource.getString("IGNORE_PATH");
		List<String> list = Arrays.asList(IGNORE_PATH.split(","));
		if (request.getServletPath().indexOf("login") != -1) {
			return true;
		}
		if (list.size() > 0) {
			for (String str : list) {
				if (request.getServletPath().indexOf(str) != -1) {
					return true;
				}
			}
		}
		
		String sessionId = request.getParameter("JSESSIONID");

		
		Object token =null;
		
		if(sessionId!=null){
			HttpSession session = MySessionContext.getSession(sessionId);
			if(session !=null){
				//权限拦截
				request.getSession().setAttribute("login_token", session.getAttribute("login_token"));
				token = request.getSession().getAttribute("login_token");
			}
		
		}else{
			
		   token = request.getSession().getAttribute("login_token");
		}

		if(token == null){
			request.getRequestDispatcher("/login").forward(request, response);
			return false;
		}
		com.wf.course.model.user.User user = Constants.LOGIN_USER.get(token);
		
		if(user == null){
			request.getRequestDispatcher("/login").forward(request, response);
			return false;
		}
		return true;
	}

	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
